package com.hd123.rumba.gwt.widget.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class LabeledDateBox extends HorizontalPanel {

  private Label label;
  private String caption;
  private DateBox dateBox;
  private boolean required;
  private boolean readOnly;

  public LabeledDateBox() {
    this("", false, false);
  }

  public LabeledDateBox(String caption) {
    this(caption, false, false);
  }

  public LabeledDateBox(String caption, boolean readOnly) {
    this(caption, false, readOnly);
  }

  public LabeledDateBox(String caption, boolean required, boolean readOnly) {
    this.caption = caption;
    this.required = required;
    this.readOnly = readOnly;

    this.setSpacing(4);
    this.label = new Label();
    this.label.setWidth("100px");
    this.dateBox = new DateBox();
    this.add(this.label);
    this.add(this.dateBox);
    this.label.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
    this.setCellVerticalAlignment(this.label, HorizontalPanel.ALIGN_MIDDLE);
  }

  protected void onLoad() {
    this.setReadOnly(this.readOnly);
    this.setCaption(this.caption);
  }

  public void addChangeListener(ChangeListener listener) {
    this.dateBox.addChangeListener(listener);
  }

  public void removeChangeListener(ChangeListener listener) {
    this.dateBox.removeChangeListener(listener);
  }

  public void focus() {
    this.dateBox.focus();
  }

  public Label getLabel() {
    return label;
  }

  public DateBox getDateBox() {
    return dateBox;
  }

  public boolean isReadOnly() {
    return readOnly;
  }

  public void setReadOnly(boolean readOnly) {
    this.readOnly = readOnly;
    this.dateBox.setReadOnly(this.readOnly);
    this.setCaption(this.caption);
  }

  public boolean isRequired() {
    return required;
  }

  public void setRequired(boolean isRequired) {
    this.required = isRequired;
    this.setCaption(caption);
  }

  public String getCaption() {
    return caption;
  }

  public void setCaption(String caption) {
    this.caption = caption;
    if (this.required && !this.readOnly) {
      DOM.setInnerHTML(this.label.getElement(), this.caption + "<font color='red'>*</font>");
    } else {
      this.label.setText(this.caption);
    }
  }

  public void setDateText(String dateText) {
    this.dateBox.setDateText(dateText);
  }

  public String getDateText() {
    return this.dateBox.getDateText();
  }

  public void setLabelWidth(String width) {
    this.label.setWidth(width);
  }

  public String getLabelWidth() {
    return String.valueOf(this.label.getOffsetWidth());
  }
}
